<template>
  <el-dialog v-model="visible" title="新增" @close="closeDialog" width="580px">
    <el-form :model="formData" ref="infoForm">
      <el-form-item
        label="类别："
        prop="category"
        :label-width="formLabelWidth"
      >
        <el-select v-model="formData.categoryId" placeholder="请选择类别">
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题：" prop="title" :label-width="formLabelWidth">
        <el-input v-model="formData.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="概况：" prop="content" :label-width="formLabelWidth">
        <el-input
          type="textarea"
          v-model="formData.content"
          placeholder="请输入内容"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="danger" @click="submit" :loading="submitLoading"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script>
import { reactive, ref } from "vue";
import { addInfo } from "@/api/news";
import { ElMessage } from "element-plus";
export default {
  name: "addDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    categories: {
      type: Array,
      default: () => [],
    },
  },
  setup(props, { emit }) {
    // 表单
    const infoForm = ref(null);
    const formLabelWidth = ref("70px");
    // 提交按钮加载状态
    const submitLoading = ref(false);

    // 表单数据
    const formData = reactive({
      categoryId: "",
      title: "",
      content: "",
    });

    // 关闭窗口
    const closeDialog = () => {
      infoForm.value.resetFields();
      emit("close");
    };

    const submit = () => {
      if (!formData.categoryId) {
        ElMessage({
          type: "error",
          message: "分类不能为空",
        });
        return false;
      }

      // 提交按钮加载状态
      submitLoading.value = true;

      let requestData = {
        categoryId: formData.categoryId,
        title: formData.title,
        content: formData.content
      }
      addInfo(requestData)
        .then((response) => {
          let data = response.data;
          ElMessage({
            type: "success",
            message: data.message,
          });

          submitLoading.value = false;
          closeDialog();
        })
        .catch((error) => {
          submitLoading.value = false;
          infoForm.value.resetFields();
        });
    };

    return {
      infoForm,
      formLabelWidth,
      formData,
      submitLoading,
      closeDialog,
      submit,
    };
  },
};
</script>
<style lang="scss" scoped>
</style>